const gulp = require('gulp');
const uglify = require('gulp-uglify');  //js 压缩工具
const rename = require('gulp-rename');  //js 重命名工具
const concat = require("gulp-concat");  //js 合并文件工具
const ts = require('gulp-typescript');  //ts 插件
const eslint = require('gulp-eslint');//eslint 插件

//测试任务 -----------------------------------
// //parallel 并行执行
// gulp.task("parallel", gulp.parallel("test","test2"));

// // series 依赖顺序执行
// gulp.task("series", gulp.series("test","test2"));

gulp.task('test', () => {
  console.log(`test`)
});

//------------------------------------------
const enginenName = "fireflyx"
const engineSrcFiles = `src/**/*.ts`;
const exampleSrcFiles = `examples/src/**/*.ts`;
const libPath = `lib/`;
const examplePath = `examples/lib/`;
const tsConfFun = ts.createProject(`src/tsconfig.json`);
const tsExampleConfFun = ts.createProject(`examples/src/tsconfig.json`);

//-------------------------合并文件----------------
let concatFile = async (path, suffix) => {
  console.log(`start concat ${path}*${suffix}`);
  return gulp.src(`${path}*${suffix}`)
    .pipe(concat(`${enginenName}${suffix}`))
    .pipe(gulp.dest(libPath))
}

let copyFile = async (fromPath, toPath) => {
  console.log(`start copyFile from ${fromPath} to  ${toPath}`);
  gulp.src(`${fromPath}/*`)
    .pipe(gulp.dest(toPath));
}

// //合并.js文件
// // gulp.task("concatjs", async () => {
// //   concatFile(srcPath, `.js`);
// // });
// gulp.task("concatjs", (cb) => {
//   console.log(`start concat JS`);
//   let suffix = ".js";
//   gulp.src([
//     //处理 js 合并的优先级
//     `dist/Math/**/*${suffix}`,
//     `dist/Rendering/renderPipeline${suffix}`,
//     `dist/Rendering/**/*${suffix}`,
//     `dist/*${suffix}`,
//     `${distPath}*${suffix}`
//   ])
//     .pipe(concat(`${enginenName}${suffix}`))
//     .pipe(gulp.dest(libPath))
//     .on("end", cb)
// });

// //合并d.ts文件
// gulp.task("concatdts", async () => {
//   concatFile(distPath, `.d.ts`);
// });

// //合并js.map文件
// gulp.task("concatjsmap", async () => {
//   concatFile(distPath, `.js.map`);
// });

// //并行合并文件任务
// gulp.task("concat", gulp.parallel("concatjs", "concatdts", "concatjsmap"));
//-------------------------------------------------------------
//ts 编译
const tsBuild = (cb, _src, _dest, _tsConfFun, _errorBreak) => {
  if (_errorBreak) {
    gulp.src(_src)
      //lint 检查 
      .pipe(eslint())
      .pipe(eslint.format())
      .pipe(eslint.failAfterError())
      //开始编译
      .pipe(_tsConfFun())
      .pipe(gulp.dest(_dest))
      .on("end", cb)
  } else {
    gulp.src(_src)
      //lint 检查 
      .pipe(eslint())
      .pipe(eslint.format())
      //开始编译
      .pipe(_tsConfFun())
      .on("error", (err) => { console.error(err) })
      .pipe(gulp.dest(_dest))
      .on("end", cb)
  }
}

//编译 引擎
gulp.task("tscEngine", (cb) => {
  tsBuild(cb, engineSrcFiles, 'lib', tsConfFun, true);
});


//编译样例
gulp.task("tscExample", (cb) => {
  tsBuild(cb, exampleSrcFiles, 'examples/dist', tsExampleConfFun, true);
});

//编译 引擎 error 不中断
gulp.task("tscEngine_nobreak", (cb) => {
  tsBuild(cb, engineSrcFiles, 'lib', tsConfFun, false);
});

//编译 样例 error 不中断
gulp.task("tscExample_nobreak", (cb) => {
  tsBuild(cb, exampleSrcFiles, 'examples/dist', tsExampleConfFun, false);
});


//lint 检查
gulp.task("lint", () => {
  return gulp.src(engineSrcFiles, exampleSrcFiles)
    //lint 检查 
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

//------------------------------------------------
//压缩js文件 min化
const minifyJS = (cb, _src, _dest, _errorBreak) => {
  if (_errorBreak) {
    gulp.src(_src)
      .pipe(uglify())       //压缩main.js
      .on("error", (err) => { throw new Error(`uglify error Break \n ${err.toString()}`); })
      .pipe(rename({ suffix: '.min' })) //重命名
      .pipe(gulp.dest(_dest))
      .on("end", cb)
  } else {
    gulp.src(_src)
      .pipe(uglify())       //压缩main.js
      .pipe(rename({ suffix: '.min' })) //重命名
      .pipe(gulp.dest(_dest))
      .on("error", (err) => { console.error(err.toString()) })
      .on("end", cb)
  }
}

//引擎js min化  
gulp.task('minifyEngine', (cb) => {
  minifyJS(cb, `${libPath}${enginenName}.js`, libPath, true);
});

//引擎js min化 error 不中断
gulp.task('minifyEngine_nobreak', (cb) => {
  minifyJS(cb, `${libPath}${enginenName}.js`, libPath, false);
});

//复制lib文件到样例
gulp.task('copyToExample', async () => {
  console.log(`copyToExample start`);
  copyFile(libPath, examplePath);
});

//-------------------------------------------------

//watch 
gulp.task("watch", () => {
  gulp.watch(engineSrcFiles, gulp.series(`tscEngine_nobreak`, `minifyEngine_nobreak`, `copyToExample`));  //监听 src 的代码修改 ，并且编译
  gulp.watch(exampleSrcFiles, gulp.series(`tscExample_nobreak`));  //监听 样例 src 的代码修改
});

//build
gulp.task("build", gulp.series(`tscEngine`, `minifyEngine`, `copyToExample`, `tscExample`));